package nl.ruudshuis.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import nl.ruudshuis.beans.BiedingBean;
import nl.ruudshuis.db.DBmanager;

public class BiedingDao {

	private String sqlBiedingread = "SELECT userId, prijs from BIEDING WHERE veilingId = ? ORDER BY prijs DESC";
	private String sqlBiedingcreate = "INSERT INTO BIEDING ( ?, ?, ?)";
	private String sqlBiedingupdate = "UPDATE BIEDING set prijs = ? WHERE veilingId = ? AND userId = ?";

	private Connection con = null;
	private PreparedStatement psRead = null;
	private PreparedStatement psUpdate = null;
	private PreparedStatement psCreate = null;

	public BiedingDao(DBmanager db) {
		DBmanager myDb = db;
		con = myDb.getConnection();
		try {

			this.psRead = con.prepareStatement(sqlBiedingread);
			this.psCreate = con.prepareStatement(sqlBiedingcreate);
			this.psUpdate = con.prepareStatement(sqlBiedingupdate);

		} catch (SQLException se) {
			printSQLException(se);
		}
	}

	public LinkedList<BiedingBean> getBiedingen(int veilingId) {

		LinkedList<BiedingBean> biedingen = new LinkedList<BiedingBean>();

		try {
			psRead.setInt(1, veilingId);
			ResultSet rs = psRead.executeQuery();

			while (rs.next()) {
				int userId = rs.getInt("userId");
				double prijs = rs.getInt("prijs");
				BiedingBean b = new BiedingBean();
			//	b.setAll(veilingId, userId, prijs);
				biedingen.add(b);
			}

			rs.close();

		} catch (SQLException se) {
			printSQLException(se);
		}

		return biedingen;
	}

	private void printSQLException(SQLException se) {
		while (se != null) {

			System.out.print("SQLException: State:   " + se.getSQLState());
			System.out.println("Severity: " + se.getErrorCode());
			System.out.println(se.getMessage());

			se = se.getNextException();
		}
	}

}
